package com.ruoyi.pos.api.service.user.impl;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.enums.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.pos.api.dto.user.TerminalManageDto;
import com.ruoyi.pos.api.service.user.ITerminalManageService;
import com.ruoyi.pos.api.utils.CommonUtils;
import com.ruoyi.pos.api.vo.user.InventoryRecordGoodsVo;
import com.ruoyi.pos.api.vo.user.InventoryRecordStatisticVo;
import com.ruoyi.pos.api.vo.user.InventoryRecordVo;
import com.ruoyi.pos.api.vo.user.TerminalInfoVo;
import com.ruoyi.pos.web.domain.*;
import com.ruoyi.pos.web.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author luobo
 * @title: TerminalManageServiceImpl
 * @projectName pos
 * @description: TODO
 * @date 2021-11-15 16:32:51
 */
@Service
public class TerminalManageServiceImpl implements ITerminalManageService {
    private static final Logger log = LoggerFactory.getLogger(TerminalManageServiceImpl.class);

    @Autowired
    private CommonUtils commonUtils; //公共业务处理类

    @Autowired
    private TUserInfoMapper userInfoMapper;
    @Autowired
    private TUserTeamInfoMapper userTeamInfoMapper;
    @Autowired
    private TStatisticInfoMapper statisticInfoMapper;
    @Autowired
    private TTerminalInfoMapper terminalInfoMapper;
    @Autowired
    private TTerminalGoodsInfoMapper terminalGoodsInfoMapper;
    @Autowired
    private TTerminalTransInfoMapper terminalTransInfoMapper;

    //查询库存管理/库存记录-头信息
    @Override
    public InventoryRecordVo queryInventoryRecord(TerminalManageDto terminalManageDto) throws Exception {
        InventoryRecordVo vo = new InventoryRecordVo();
        //计算自己的终端数
        String userId = commonUtils.getUserId();
        TTerminalInfo mapper = new TTerminalInfo();
        mapper.setUserId(userId);
        mapper.setGoodsId(terminalManageDto.getGoodsId());
        mapper.setBrandId(terminalManageDto.getBrandId());
        List<TTerminalInfo> all = terminalInfoMapper.selectTTerminalInfoList(mapper); //查询全部数据
        List<TTerminalInfo> activated = all.stream().filter(bean ->ActivateStatusEnum.ACTIVATED.getCode().equals(bean.getActivateStatus())).collect(Collectors.toList()); //获取已激活总数
        List<TTerminalInfo> inactivated = all.stream().filter(bean ->ActivateStatusEnum.INACTIVATED.getCode().equals(bean.getActivateStatus())).collect(Collectors.toList()); //获取未激活总数
        vo.setTotalTerminal(all.size() + "");//终端总数
        vo.setTotalTerminalActivated(activated.size() + "");//已激活终端总数
        vo.setTotalTerminalInactivated(inactivated.size() + "");//未激活终端总数
        return vo;
    }

    //查询库存管理-根据品牌查询
    @Override
    public List<InventoryRecordGoodsVo> queryInventoryManagementByBrand(TerminalManageDto terminalManageDto) throws Exception {
        //根据品牌id查询品牌下的所有商品
        TTerminalGoodsInfo goodsMapper = new TTerminalGoodsInfo();
        goodsMapper.setBrandId(terminalManageDto.getBrandId());
        List<TTerminalGoodsInfo> goodsList = terminalGoodsInfoMapper.selectTTerminalGoodsInfoList(goodsMapper);
        List<InventoryRecordGoodsVo> goodsVoList = new ArrayList<InventoryRecordGoodsVo>();
        Optional.ofNullable(goodsList).ifPresent(list ->{
            list.stream().forEach(goods ->{
                InventoryRecordGoodsVo vo = new InventoryRecordGoodsVo();
                vo.setGoodsId(goods.getId());
                BeanUtils.copyProperties(goods, vo);
                //计算自己的终端数
                String userId = commonUtils.getUserId();
                TTerminalInfo mapper = new TTerminalInfo();
                mapper.setUserId(userId);
                mapper.setGoodsId(goods.getId());
                List<TTerminalInfo> all = terminalInfoMapper.selectTTerminalInfoList(mapper); //查询全部数据
                List<TTerminalInfo> activated = all.stream().filter(bean -> ActivateStatusEnum.ACTIVATED.getCode().equals(bean.getActivateStatus())).collect(Collectors.toList()); //获取已激活总数
                List<TTerminalInfo> inactivated = all.stream().filter(bean ->ActivateStatusEnum.INACTIVATED.getCode().equals(bean.getActivateStatus())).collect(Collectors.toList()); //获取未激活总数
                vo.setTotalTerminal(all.size() + "");//终端总数
                vo.setTotalTerminalActivated(activated.size() + "");//已激活终端总数
                vo.setTotalTerminalInactivated(inactivated.size() + "");//未激活终端总数
                goodsVoList.add(vo);
            });
        });

        return goodsVoList;
    }

    //查询库存记录-根据品牌查询
    @Override
    public InventoryRecordStatisticVo queryInventoryRecordByBrand(TerminalManageDto terminalManageDto) throws Exception {
        InventoryRecordStatisticVo vo = new InventoryRecordStatisticVo();
        //计算自己
        String userId = commonUtils.getUserId();
        List<String> userIds = new ArrayList<String>();
        userIds.add(userId);
        TStatisticInfo info = statisticInfoMapper.selectTStatisticInfoByUserIds(userIds, terminalManageDto.getBrandId(), "", "");
        vo.setMyTotalBuy(null == info ? BigDecimal.ZERO : info.getMyBuyTerminalNum());
        vo.setMyTotalExchange(null == info ? BigDecimal.ZERO : info.getMyExchangelTerminalNum());
        //计算直营
        TUserTeamInfo mapper = new TUserTeamInfo();
        mapper.setUserId(userId);
        mapper.setTeamType(TeamTypeEnum.DIRECTLY.getCode());
        List<TUserTeamInfo> teams = userTeamInfoMapper.selectTUserTeamInfoList(mapper);
        userIds = teams.stream().map(TUserTeamInfo::getSubUserId).distinct().collect(Collectors.toList());
        log.info("-1---" + userIds);
        info = statisticInfoMapper.selectTStatisticInfoByUserIds(userIds, terminalManageDto.getBrandId(), "", "");
        vo.setDirectlyTotalBuy(null == info ? BigDecimal.ZERO : info.getMyBuyTerminalNum());
        vo.setDirectlyTotalExchange(null == info ? BigDecimal.ZERO : info.getMyExchangelTerminalNum());
        //计算团队
        mapper.setTeamType(TeamTypeEnum.TEAM.getCode());
        teams = userTeamInfoMapper.selectTUserTeamInfoList(mapper);
        userIds = teams.stream().map(TUserTeamInfo::getSubUserId).distinct().collect(Collectors.toList());
        log.info("-2---" + userIds);
        info = statisticInfoMapper.selectTStatisticInfoByUserIds(userIds, terminalManageDto.getBrandId(), "", "");
        vo.setTeamTotalBuy(null == info ? BigDecimal.ZERO : info.getMyBuyTerminalNum());
        vo.setTeamTotalExchange(null == info ? BigDecimal.ZERO : info.getMyExchangelTerminalNum());
        return vo;
    }

    //查询终端列表
    @Override
    public Map<String, Object> queryTerminalList(TerminalManageDto terminalManageDto) throws Exception {
        Map<String, Object> resultPage = new HashMap<String, Object>();
        String userId = commonUtils.getUserId();
        TTerminalInfo mapper = new TTerminalInfo();
        BeanUtils.copyProperties(terminalManageDto, mapper);
        mapper.setUserId(userId);
        PageUtil.startPage(terminalManageDto);
        List<TTerminalInfo> terminalInfoList = terminalInfoMapper.queryUserTerminalList(mapper); //查询分页数据
        //查询接收人是我的终端记录
        TTerminalTransInfo transInfo = new TTerminalTransInfo();
        transInfo.setTransInUserId(userId);//查询接收的终端记录
        List<TTerminalTransInfo> tTerminalTransInfos = terminalTransInfoMapper.selectTTerminalTransInfoList(transInfo);
        List<TerminalInfoVo> voList = new ArrayList<TerminalInfoVo>();
        resultPage.put("total", 0L);
        Optional.ofNullable(terminalInfoList).ifPresent(lists ->{
            resultPage.put("total", new PageInfo(lists).getTotal());
            lists.stream().forEach(bean ->{
                TerminalInfoVo vo = new TerminalInfoVo();
                BeanUtils.copyProperties(bean, vo);
                if (YesOrNoEnums.NO.getCode().equals(vo.getBindingStatus())) {
                    vo.setBindingStatusShow("已绑定");
                } else {
                    vo.setBindingStatusShow("未绑定");
                }
                if (StringUtils.isNotEmpty(vo.getTransStatus())) {
                    vo.setTransStatusShow(TransStatusEnum.getEnumsByCode(vo.getTransStatus()).getValue());
                }
                if (StringUtils.isNotEmpty(vo.getTerminalType())) {
                    vo.setTerminalTypeShow(TerminalTypeEnum.getEnumsByCode(vo.getTerminalType()).getValue());
                }
                Optional.ofNullable(tTerminalTransInfos).ifPresent(map ->{
                    map.stream().forEach(type ->{
                        if (bean.getSnCode().equals(type.getSnCode())){
                            vo.setTransType(YesOrNoEnums.YES.getCode());//（0:前端显示划回钮）
                        }
                    });
                });

                voList.add(vo);
            });
        });
        resultPage.put("list", voList);
        return resultPage;
    }

    //划拨（划出）
    @Override
    @Transactional
    public void terminalTransferOut(TerminalManageDto terminalManageDto) throws Exception {
        if (StringUtils.isEmpty(terminalManageDto.getTransInUserId())) {
            throw new RuntimeException("请选择划拨接收人");
        }
        String userId = commonUtils.getUserId();
        //写入划拨记录表
        Date date = DateUtils.getNowDate();
        TTerminalTransInfo trans = new TTerminalTransInfo();
        trans.setId(IdUtils.simpleUUID());
        trans.setTransOutUserId(userId);
        trans.setTransInUserId(terminalManageDto.getTransInUserId());
        trans.setSnCode(terminalManageDto.getSnCode());
        trans.setTransStatus(TransStatusEnum.WAIT_CONFIIRM.getCode());
        trans.setCreateTime(date);
        trans.setTransOutTime(date);
        trans.setTransType(YesOrNoEnums.YES.getCode());
        terminalTransInfoMapper.insertTTerminalTransInfo(trans);

        //更新终端的userId
        TTerminalInfo mapper = new TTerminalInfo();
        mapper.setSnCode(terminalManageDto.getSnCode());
        List<TTerminalInfo> list = terminalInfoMapper.selectTTerminalInfoList(mapper);
        TTerminalInfo terminal = Optional.ofNullable(list).get().get(0);
        //....更新终端状态
        terminal.setTransStatus(TransStatusEnum.WAIT_CONFIIRM.getCode());
        terminalInfoMapper.updateTTerminalInfo(terminal);
    }

    //划拨（划回）
    @Override
    @Transactional
    public void terminalTransferBack(TerminalManageDto terminalManageDto) throws Exception {
        String userId = commonUtils.getUserId();
        TUserInfo user = userInfoMapper.selectTUserInfoByUserId(userId);
        //写入划拨记录表
        Date date = DateUtils.getNowDate();
        TTerminalTransInfo trans = new TTerminalTransInfo();
        trans.setId(IdUtils.simpleUUID());
        trans.setTransOutUserId(userId);
        trans.setTransInUserId(user.getSuperiorUserId());
        trans.setSnCode(terminalManageDto.getSnCode());
        trans.setTransStatus(TransStatusEnum.WAIT_CONFIIRM.getCode());
        trans.setCreateTime(date);
        trans.setTransInTime(date);
        trans.setTransType(YesOrNoEnums.NO.getCode());
        terminalTransInfoMapper.insertTTerminalTransInfo(trans);

        //更新终端的userId
        TTerminalInfo mapper = new TTerminalInfo();
        mapper.setSnCode(terminalManageDto.getSnCode());
        List<TTerminalInfo> list = terminalInfoMapper.selectTTerminalInfoList(mapper);
        TTerminalInfo terminal = Optional.ofNullable(list).get().get(0);
        //....更新终端状态
        terminal.setTransStatus(TransStatusEnum.WAIT_CONFIIRM.getCode());
        terminalInfoMapper.updateTTerminalInfo(terminal);
    }

}
